package cn.tedu.luban.demand.webapi.service.impl;

import cn.tedu.luban.commons.exception.LubanServiceException;
import cn.tedu.luban.commons.pojo.demand.dto.RequestOrderDTO;
import cn.tedu.luban.commons.pojo.demand.dto.RequestOrderListDTO;
import cn.tedu.luban.commons.pojo.demand.model.AccessProvider;
import cn.tedu.luban.commons.pojo.demand.model.RequestOrder;
import cn.tedu.luban.commons.pojo.demand.vo.RequestOrderListItemVO;
import cn.tedu.luban.commons.pojo.demand.vo.RequestOrderVO;
import cn.tedu.luban.commons.restful.JsonPage;
import cn.tedu.luban.commons.restful.ResponseCode;
import cn.tedu.luban.commons.utils.PropertiesUtils;
import cn.tedu.luban.demand.service.IRequestOrderService;
import cn.tedu.luban.demand.webapi.mapper.AccessProviderMapper;
import cn.tedu.luban.demand.webapi.mapper.RequestOrderMapper;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.List;

@Service
@Slf4j
@DubboService
public class RequestOrderService implements IRequestOrderService {
    @Autowired
    private RequestOrderMapper requestOrderMapper;

    @Autowired
    private AccessProviderMapper accessProviderMapper;

    //新增需求单
    @Override
    public Long saveRequestOrder(RequestOrderDTO requestOrderDTO) {
        //实例化对应数据库的实体类
        RequestOrder requestOrder = new RequestOrder();
        //将前端传入的参数中同名属性赋值给实体类
        BeanUtils.copyProperties(requestOrderDTO, requestOrder);
        //再将一些默认值赋值
        requestOrder.setRequestOrderNo(requestOrderDTO.getRequestOrderNo());
        requestOrder.setGmtCreate(System.currentTimeMillis());
        requestOrder.setGmtModified(requestOrder.getGmtCreate());
        requestOrder.setStatus(1);
        requestOrder.setCreateUserId(99L);
        requestOrder.setModifiedUserId(99L);
        requestOrder.setCreateUserName("root");
        requestOrder.setModifiedUserName("root");
        requestOrder.setProviderId(6);
        //新增到数据库
        requestOrderMapper.insert(requestOrder);
        return requestOrder.getId();
    }

    //分页查询需求单
    @Override
    public JsonPage<RequestOrderListItemVO> queryRequestOrderList(
            RequestOrderListDTO requestOrderListDTO,
            Integer pageNo,
            Integer pageSize) {
        //设置分页条件
        PageHelper.startPage(pageNo, pageSize);
        //查询所有符合条件的需求单
        List<RequestOrder> list =
                requestOrderMapper.queryRequestOrders(requestOrderListDTO);
        //将集合泛型转换为RequestOrderListItemVO类型
        List<RequestOrderListItemVO> voList =
                PropertiesUtils.copyListProperties(
                        list, RequestOrderListItemVO.class);
        for (int i = 0; i < list.size(); i++) {
            //取出集合中的元素
            RequestOrderListItemVO vo = voList.get(i);
            //给未被赋值的属性赋值
            vo.setCategoryId(list.get(i).getOrderCategoryId());
            vo.setCreateTime(list.get(i).getGmtCreate());
            //分润比例的获取，先根据当前RequestOrder对象的providerId获取商家信息
            AccessProvider accessProvider =
                    accessProviderMapper.getEntity(
                            list.get(i).getProviderId() * 1L);
            //判断供应商是否为空
            if (accessProvider != null) {
                //获取分润比例
                BigDecimal profitScale = accessProvider.getProfitScale();
                //根据分润比例计算工人师傅本单的金额，师傅看到的金额是减去分润比例后的金额
                Long workerAmount =
                        getWorkerAmount(list.get(i).getOrderAmount(), profitScale);
                //设置订单金额
                vo.setViewOrderAmount(workerAmount);
                vo.setProfitScale(profitScale);
            }
        }
        return JsonPage.restPage(new PageInfo<>(voList));
    }

    //price价格，scale分润比例
    private Long getWorkerAmount(Long price, BigDecimal scale) {
        //判断分润比例是否为空，multiply表示乘以，divide表示除以，subtract表示减去
        if (scale != null) {// 将价格转换为 BigDecimal 类型，以进行精确的计算
            //例如100*(100-20)/100
            return new BigDecimal(price).
                    //用100减去折扣比例，然后与价格相乘
                            multiply(new BigDecimal(100).subtract(scale)).
                    //将结果除以100，以还原为原始价格
                            divide(new BigDecimal(100)).
                    //将计算结果转换为long类型，并返回
                            longValue();
        }
        //默认20
        return new BigDecimal(price).
                multiply(new BigDecimal(20)).
                divide(new BigDecimal(100)).
                longValue();
    }

    //单查需求单
    @Override
    public RequestOrderVO getRequestOrder(String requestOrderNo) {
        RequestOrder requestOrder =
                requestOrderMapper.getRequestOrderByOrderNo(requestOrderNo);
        if (requestOrder == null) {
            throw new LubanServiceException(
                    ResponseCode.INTERNAL_SERVER_ERROR, "需求单不存在");
        }
        RequestOrderVO requestOrderVO = new RequestOrderVO();
        BeanUtils.copyProperties(requestOrder, requestOrderVO);
        requestOrderVO.setCategoryId(requestOrder.getOrderCategoryId());
        requestOrderVO.setCreateTime(requestOrder.getGmtCreate());
        System.out.println("accessProviderMapper:" + accessProviderMapper);
        AccessProvider accessProvider =
                accessProviderMapper.getEntity(
                        requestOrder.getProviderId() * 1L);
        if (accessProvider != null) {
            //供应商分润比例
            BigDecimal profitScale = accessProvider.getProfitScale();
            Long workerAmount = getWorkerAmount(
                    requestOrder.getOrderAmount(), profitScale);
            //订单金额
            requestOrderVO.setViewOrderAmount(workerAmount);
        }
        return requestOrderVO;
    }

    //抢单
    @Override
    public Object grabOrder(String requestOrderId) {
        return requestOrderMapper.grabOrder(requestOrderId);
    }

    //取消抢单
    @Override
    public Object cancelGrabOrder(String requestOrderId) {
        return requestOrderMapper.cancelGrabOrder(requestOrderId);
    }
}
